home *** CD-ROM | disk | FTP | other *** search
- Path: gail.ripco.com!mambuhl
- From: mambuhl@ripco.com (Martin Ambuhl)
- Newsgroups: comp.lang.c
- Subject: Re: Calling a Function Tw
- Date: 4 Mar 1996 09:19:59 GMT
- Organization: Ripco Communications, Inc.
- Message-ID: <4hecjv$p7s@gail.ripco.com>
- NNTP-Posting-Host: foley.ripco.com
-
- razine@aol.com (Razine) in <4he6q9$6r6@newsbf02.news.aol.com> asks:
-
- >I am trying to call a function twice from my program on the same printf
- >line and have run into a small problem. i was wondering if someone can
- >explain how to fix it.
-
- Learn the correct use of the switch construct. As usual, I have
- appended a revision of your code at the EOM, in which my changes and
- comments are flagged with `/* mha - ... */'. And, as usual, some of the
- changes reflect judgements about good practice rather than corrections
- of errors.
-
- [original code snipped]
-
- >Now with this function, the printf line will display 0 for the first one
- >and garbage for the second one..
-
- I don't believe you. Your original function should have returned 1 for
- 0 or 1 as an argument, randomness for all others.
-
- #include <stdio.h> /* mha - added. Necessary for printf */
- int num(int); /* mha - added prototype. Not needed
- * in this case, but the habit of
- * prototyping functions can prove
- * invaluable. */
-
- int /* mha - was `void' */ main(void)
- {
- printf("First Number is %d , the Second is %d \n", num(0), num(1));
- /* mha - fixed inconsequential typo in above */
- return 0; /* mha - added explicit return
- * [optional] */
- }
-
- int num(int index)
- {
- int return_number;
- switch (index) {
- case 0:
- return_number = 0;
- break; /* mha - added. Necessary unless you
- * want to fall through to the next
- * case. This ain't Pascal. */
- case 1:
- return_number = 1;
- break; /* mha - added. */
- default: /* mha - added. Without this,
- * return_number which is an
- * uninitialized auto variable and will
- * contain God-knows-what when index is
- * outside of [0,1] */
- return_number = 2; /* mha - added. */
- }
- return (return_number);
- /* mha - Note that this function body is unnecessarily verbose,
- * even before my additions. Also note that the above statement can
- * be written `return return_number;' */
- }
-
- --
- * Martin Ambuhl net: mambuhl@ripco.com
- * Chicago, IL (USA)
-